<?php

namespace App\Http\Controllers\Auth;

use Auth;
use JWTAuth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    //
    use AuthenticatesUsers;

    public function __construct()
    {
//		$this->middleware('guest')->except('logout');
    }


    /**
     * 处理用户登录逻辑
     *
     * Date: 2018/7/18
     * @author Leon
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
        $guard = $request->get('guard');

        if(empty($guard)){
            return response()->json([
                'error' => '您的账号无此权限!'
            ], 403);
        }
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return failed('认证失败，用户名或密码不正确',401);
            }
        } catch (JWTException $exception) {
            return internalError();
        }

        if(Auth::user()->status == 0){
            return failed('你的账号已被禁用!',402);
        }

        $user = Auth::user();
        $user_manager = $user->is_manage;

        switch($user_manager){
            case '1':
                if($guard > 1){
                    return failed('您的账号无此权限!',403);
                }
                break;
            case '2':
                if($guard == 3){
                    return failed('您的账号无此权限!',403);
                }
                break;
            case '3':
                if($guard <3){
                    return failed('您的账号无此权限!',403);
                }
        }

        return success([
            'id' => $user->id,
            'name' => $user->name,
            'phone' => $user->phone,
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => config('jwt.ttl') * 60,
        ]);
    }

    public function api_logout()
    {
        try {
            $this->guard()->logout();
        } catch (Exception $exception) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unknown Error'
            ], 500);
        }
        return response()->json([
            'status' => 'success',
            'message' => '注销成功'
        ]);
    }

    /**
     * 定义用于验证的用户的字段
     *
     * Date: 2018/1/25
     * @author Leon
     * @return string
     */
    public function username()
    {
        return 'phone';
    }


}
